<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="语言" prop="languageVersion">
        <el-input v-model="queryParams.languageVersion" placeholder="请输入语言" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="播放时间" prop="playTime">
        <el-input v-model="queryParams.playTime" placeholder="请输入播放时间" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="散场时间" prop="endTime">
        <el-input v-model="queryParams.endTime" placeholder="请输入散场时间" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="场次日期" prop="sessionDate">
        <el-date-picker clearable v-model="queryParams.sessionDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择场次日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="票价" prop="sessionPrice">
        <el-input v-model="queryParams.sessionPrice" placeholder="请输入票价" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['cine:session:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['cine:session:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['cine:session:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['cine:session:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sessionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="影厅编号" align="center" prop="hallId" />
      <el-table-column label="语言" align="center" prop="languageVersion" />
      <el-table-column label="电影" align="center" prop="movieId" />
      <el-table-column label="播放时间" align="center" prop="playTime" />
      <el-table-column label="散场时间" align="center" prop="endTime" />
      <el-table-column label="场次日期" align="center" prop="sessionDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.sessionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="票价" align="center" prop="sessionPrice" />
      <el-table-column label="提示" align="center" prop="sessionTips" />
      <el-table-column label="总座位数" align="center" prop="seatNums" />
      <el-table-column label="售出座位数" align="center" prop="sallNums" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['cine:session:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['cine:session:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改场次信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body class="custom-dialog">
      <el-form ref="sessionRef" :model="form" :rules="rules" label-width="100px" class="custom-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="语言" prop="languageVersion" class="custom-form-item">
              <el-input v-model="form.languageVersion" placeholder="请输入语言版本" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="播放时间" prop="playTime" class="custom-form-item">
              <el-input v-model="form.playTime" placeholder="请输入播放时间" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="散场时间" prop="endTime" class="custom-form-item">
              <el-input v-model="form.endTime" placeholder="请输入散场时间" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场次日期" prop="sessionDate" class="custom-form-item">
              <el-date-picker clearable v-model="form.sessionDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择场次日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="票价" prop="sessionPrice" class="custom-form-item">
              <el-input v-model="form.sessionPrice" placeholder="请输入票价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售出座位数" prop="sallNums" class="custom-form-item">
              <el-input v-model="form.sallNums" placeholder="请输入售出座位数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="影厅提示" prop="sessionTips" class="custom-form-item">
              <editor v-model="form.sessionTips" :min-height="192" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <div class="movie-seat-container">
    <!-- 触发按钮 -->
    <button class="open-popup-btn" @click="showPopup = true">选择座位</button>

    <!-- 弹窗遮罩层 -->
    <div class="popup-overlay" v-if="showPopup" @click="showPopup = false"></div>

    <!-- 选座弹窗 -->
    <div class="seat-popup" v-if="showPopup">
      <div class="popup-header">
        <span class="cinema-name">{{ cinemaName }}</span>
        <button class="close-btn" @click="showPopup = false">×</button>
      </div>

      <div class="screen-area">
        <div class="screen"></div>
        <div class="screen-text">{{ hallName }}</div>
      </div>

      <div class="seats-container">
        <div class="row-labels">
          <div v-for="row in Object.keys(seats)" :key="`row-${row}`" class="row-label">
            {{ row }}
          </div>
        </div>

        <div class="seats-grid">
          <div v-for="(rowSeats, row) in seats" :key="`row-${row}`" class="seat-row">
            <div v-for="(seatStatus, index) in rowSeats" :key="`seat-${row}-${index}`" class="seat" :class="{
              'seat-available': seatStatus === 0,
              'seat-empty': seatStatus === 1,
              'seat-selected': seatStatus === 2,
              'seat-sold': seatStatus === 3
            }" @click="toggleSeatSelection(row, index)">
              <span v-if="seatStatus === 3" class="sold-icon">售</span>
            </div>
          </div>
        </div>
      </div>

      <div class="seat-legend">
        <div class="legend-item">
          <div class="legend-box seat-available"></div>
          <span>可选</span>
        </div>
        <div class="legend-item">
          <div class="legend-box seat-sold"><span class="sold-text">售</span></div>
          <span>已售</span>
        </div>
        <div class="legend-item">
          <div class="legend-box seat-empty"></div>
          <span>不可售</span>
        </div>
      </div>

      <div class="selected-info" v-if="selectedSeats.length > 0">
        <div>已选座位:
          <span v-for="(seat, index) in selectedSeats" :key="index" class="selected-seat-tag">
            {{ seat.row }}排{{ seat.seat }}座
            <span class="remove-seat" @click.stop="removeSeat(index)">×</span>
          </span>
        </div>
        <div class="total-price">总价: ¥{{ (selectedSeats.length * sessionData.session_price).toFixed(2) }}</div>
        <button class="confirm-btn">确认选座</button>
      </div>
    </div>
  </div>
</template>

<script setup name="Session">
import { listSession, getSession, delSession, addSession, updateSession } from "@/api/cine/session";

const { proxy } = getCurrentInstance();

const sessionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    hallId: null,
    languageVersion: null,
    movieId: null,
    playTime: null,
    endTime: null,
    deadline: null,
    sessionDate: null,
    sessionPrice: null,
    sessionTips: null,
    sessionSeats: null,
    seatNums: null,
    sallNums: null,
    delState: null
  },
  rules: {
    hallId: [
      { required: true, message: "影厅编号不能为空", trigger: "blur" }
    ],
    languageVersion: [
      { required: true, message: "语言版本不能为空", trigger: "blur" }
    ],
    movieId: [
      { required: true, message: "电影编号不能为空", trigger: "blur" }
    ],
    playTime: [
      { required: true, message: "播放时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "散场时间不能为空", trigger: "blur" }
    ],
    deadline: [
      { required: true, message: "检测到的截止时间，没过这个时间不能删电影、影厅信息不能为空", trigger: "blur" }
    ],
    sessionDate: [
      { required: true, message: "场次日期不能为空", trigger: "blur" }
    ],
    sessionPrice: [
      { required: true, message: "票价不能为空", trigger: "blur" }
    ],
    sessionSeats: [
      { required: true, message: "座位信息，采用{key: [], key: []}存储每一个座位的状态，其中key表示排，数组(下标+1)表示几号座，存储的值为0表示可选，1表示空(无座位)，值为2表示已选择，值为3表示已售出，不能为空", trigger: "blur" }
    ],
    sallNums: [
      { required: true, message: "售出座位数不能为空", trigger: "blur" }
    ],
    delState: [
      { required: true, message: "删除标记，0未删除，1删除，默认0不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询场次信息管理列表 */
function getList() {
  loading.value = true;
  listSession(queryParams.value).then(response => {
    sessionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    sessionId: null,
    hallId: null,
    languageVersion: null,
    movieId: null,
    playTime: null,
    endTime: null,
    deadline: null,
    sessionDate: null,
    sessionPrice: null,
    sessionTips: null,
    sessionSeats: null,
    seatNums: null,
    sallNums: null,
    delState: null
  };
  proxy.resetForm("sessionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.sessionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加场次信息管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _sessionId = row.sessionId || ids.value
  getSession(_sessionId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改场次信息管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["sessionRef"].validate(valid => {
    if (valid) {
      if (form.value.sessionId != null) {
        updateSession(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSession(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _sessionIds = row.sessionId || ids.value;
  proxy.$modal.confirm('是否确认删除场次信息管理编号为"' + _sessionIds + '"的数据项？').then(function () {
    return delSession(_sessionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('cine/session/export', {
    ...queryParams.value
  }, `session_${new Date().getTime()}.xlsx`)
}

getList();

</script>
